<template>
    <form class="validate-form-container">
        <slot name="default"></slot>
        <div class="submit-area" @click.prevent="handleFormSubmit">
            <slot name="submit">
                <button type="submit" class="btn btn-primary">提交</button>
            </slot>
        </div>
    </form>
</template>

<script lang="ts">
import { defineComponent ,onUnmounted } from 'vue';
import mitt, { Emitter } from 'mitt';

type ValidateFunc = () => boolean;

type Events = {
  formItemCreated: ValidateFunc
}

export const emitter = mitt<Events>();

// mitt 3.x 版本带来 ts 错误
// type Emits<EventType extends string | symbol, T> = {
//   on(type: EventType, handler: (arg: T) => void): void
//   off(type: EventType, handler: (arg: T) => void): void
//   emit(type: EventType, arg: T): void
// }

// 存在多个定义变量时，& 符号连接Emits
// type Emitter = Emits<'a', number> & Emits<'b', string>;

export default defineComponent({
    emits: ['form-submit'],
    setup(props, context) {
        let funcArr: ValidateFunc[] = [];
        
        // 用来接收 validate-input 成功 or 失败的消息
        const callback = (func: ValidateFunc): void => {
            funcArr.push(func);
        }
        // 重载 error
        emitter.on("formItemCreated", callback);

        const handleFormSubmit = () => {
            if (funcArr.length === 0 || !funcArr) {
                return false;
            }
            const result = funcArr.map(func => func()).every(res => {
                return res;
            });
            // console.log("you click the form-submit, the validation result is =>", result);
            context.emit('form-submit', result);
        }

        onUnmounted(() => {
            emitter.off('formItemCreated', callback);
            funcArr = [];
        });

        return {
            handleFormSubmit
        }
    }
})
</script>